package com.jyu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jyu.config.MinioConfig;
import com.jyu.domain.Group;
import com.jyu.domain.Position;
import com.jyu.service.GroupService;
import com.jyu.utils.MinioUtils;
import com.jyu.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/group")
public class GroupController {

    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private GroupService groupService;

    @GetMapping
    public R getAll(){
        return new R(true,groupService.list());
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Group group) {

        IPage<Group> page = groupService.getPage(currentPage, pageSize, group);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = groupService.getPage((int) page.getPages(), pageSize, group);//一次性删除过多可能有bug
        }
        return new R(true, page);
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(groupService.getById(id));
    }

    @PutMapping
    public R checkById(@RequestBody Group group){
        return new R(groupService.check(group));
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }
}
